<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-input v-model="query" placeholder="请输入查询关键词" @input="onQueryChanged"/>
      </div>
    </template>

    <el-tree-v2 ref="treeRef" :data="treeData" :props="treeProps" :highlight-current="true" :expand-on-click-node="false"
                :height="488" :item-size="30" :filter-method="filterMethod" @node-click="editNodeData"
                :default-expanded-keys="defaultExpandedKeys"/>

  </el-card>
</template>
<script setup lang="ts">
import {ref, computed} from "vue";
import {ElTreeV2} from 'element-plus'
import type {TreeNodeData, TreeNode} from 'element-plus/es/components/tree-v2/src/types'

const {modelValue} = defineProps(['modelValue']);
const query = ref('');
const treeRef = ref<InstanceType<typeof ElTreeV2>>()
const treeProps = {
  value: 'id',
  label: 'label',
  children: 'children',
}

const treeData = computed(() => {
  const category = modelValue.category;
  const master = modelValue.master;
  const masterArr = [];
  for (let key in master) {
    const nodeArr: any = [];
    masterArr.push({id: category + "_" + key, label: key, children: nodeArr})
    for (let nodeKey in master[key].node) {
      const varArr: any = [];
      nodeArr.push({id: category + "_" + key + "_" + nodeKey, label: nodeKey, children: varArr});
      for (let varName in master[key].node[nodeKey]?.variable) {
        varArr.push({
          id: category + "_" + key + "_" + nodeKey + "_" + varName,
          label: varName,
          children: null
        })
      }
    }
  }
  return [{id: category || '', label: category || '新业务分类', children: masterArr}];
});

const expanedKeys: string[] = []
for (const datum of treeData.value) {
  const children = datum.children
  if (children) {
    expanedKeys.push(datum.id)
    children.forEach(c => {
      if (c.children) {
        expanedKeys.push(c.id)
      }
    })
  }
}

const defaultExpandedKeys = ref(expanedKeys)

const onQueryChanged = (query: string) => {
  treeRef.value!.filter(query)
}
const filterMethod = (query: string, node: TreeNode) => {
  return node.label!.includes(query)
}
const emits = defineEmits(["node-click"]);
const editNodeData = (data: TreeNodeData, node: TreeNode, e: MouseEvent) => {
  emits("node-click", data, node, e);
}
</script>
<script lang="ts">
export default {
  name: "SillyCategoryJsonTree",
  props: {modelValue: {}}
}
</script>

<style scoped>

</style>